'use strict';

/* Controllers */
app.controller('houseOwnerUserProfileCtl', function($scope,$http,rest,$compile,$location,ngDialog,user,$state,$window,uiLoad,$rootScope,$ocLazyLoad) {
    var token = $window.localStorage.getItem("token");
    
    //方法级权限
    var accessStr = $window.localStorage.getItem("accessStr");
    $scope.btns = {
    	add: 'innjia',  //新建
    	delete: 'innjia',  //删除
    	edit: 'innjia',  //编辑
    	jurisdiction: 'innjia',  //权限分配
    	resetPasswords: 'innjia',  //重置密码
    	addmember: 'innjia',  //添加成员
    	exportExcel: 'innjia', //导出表格
    	batchExportImg: 'innjia',  //批量导出图片
    	details: 'innjia',  //详情
    	rent: 'innjia',  //租赁PDF
    	list: 'innjia'  //列表
    }
    //延迟执行 - 当左侧菜单生产完毕再获取当前菜单的ID 利用ui-sref-active有且只有一个active即当前的特性用jq去获取预先存储在菜单上的id
    user.response().then(function(res){
    	var nowId = $(document).find(".navItem.active").attr("data-id");
    	rest.decoJava({
		   	 type: "post",
		     url: "/tenancy-sys/admin/menu/detail/"+nowId,
		     data: "",
		     //contentType:"application/json",
		     beforeSend: function(request){
				request.setRequestHeader("token", token); 
			},
		    success: function(data){ 
		    	console.log(data)
			    if(data.code == "0000"){
				    //匹配权限
				    angular.forEach(data.result.menuMethods,function(data){
				    	if(data.methodTagName == "add"){
				    		$scope.btns.add = data.id;
				    	} else if(data.methodTagName == "delete"){
				    		$scope.btns.delete = data.id;
				    	} else if(data.methodTagName == "edit"){
				    		$scope.btns.edit = data.id;
				    	} else if(data.methodTagName == "jurisdiction"){
				    		$scope.btns.jurisdiction = data.id;
				    	} else if(data.methodTagName == "resetPasswords"){
				    		$scope.btns.resetPasswords = data.id;
				    	} else if(data.methodTagName == "addmember"){
				    		$scope.btns.addmember = data.id;
				    	} else if(data.methodTagName == "exportExcel"){
				    		$scope.btns.exportExcel = data.id;
				    	} else if(data.methodTagName == "batchExportImg"){
				    		$scope.btns.batchExportImg = data.id;
				    	} else if(data.methodTagName == "details"){
				    		$scope.btns.details = data.id;
				    	} else if(data.methodTagName == "rent"){
				    		$scope.btns.rent = data.id;
				    	} else if(data.methodTagName == "list"){
				    		$scope.btns.list = data.id;
				    	}
				    })
			    } else if(data.message == "菜单Id有误！！！"){
			    	// $window.location.reload();
			    } else{
			    	layer.msg(data.message+'请刷新试试', {
			        	offset:'t',
			        	icon: 2
					});
			    }
		    }
	    });

    })
    
    //自定义方法状态数据
	$scope.methodsStatus = [
	        {
	            "status" : "AVAILABLE",
	            "menuName" : "可用"
	        },
	        {
	            "status" : "FORBID",
	            "menuName" : "禁止"
	        },
	        {
	            "status" : "DELETE",
	            "menuName" : "删除"
	        },
	        {
	            "status" : "",
	            "menuName" : "全部"
	        }
	    ];
	$scope.itemStatus = $scope.methodsStatus[0]; //默认为可用
    
    var tabHeight = ($window.innerHeight - 274)+"px"; //table内容区高度
    $scope.dataTableSettings = {
        "sAjaxSource": "/tenancy-sys/admin/user/list",
        // "dom": "tipr",
        "bFilter": true,  //搜索
         "sScrollY": tabHeight,  //给定高度，内容超出即出滚动条
         "bScrollCollapse": false,  //不管内容多少高度固定
         "aLengthMenu": [25,50,100,200],
         "iDisplayLength": 25,
         "sDom": '<"top">rt<"bottom"lip><"clear">', //位置 l-每页显示数量,f-过滤输入,t-表单Table,i-信息,p-翻页
         "bAutoWidth": true,  //自适应列宽
        "aoColumns": [
        	{
        		"mDataProp": "",
                "sDefaultContent": "",
                "sClass": "center handle-ck"
        	},
            {
                "mDataProp": "userName",
                "sTitle": "姓名",
                "sDefaultContent": "",
                "sClass": "center failure"
            },{
                "mDataProp": "loginName",
                "sTitle": "登录账号",
                "sDefaultContent": "",
                "sClass": "center"
            }, {
                "mDataProp": "mobile",
                "sTitle": "手机",
                "sDefaultContent": "",
                "sClass": "center"
            }, {
                "mDataProp": "email",
                "sTitle": "邮箱",
                "sDefaultContent": "",
                "sClass": "center"
            }, {
                "mDataProp": "jobNumber",
                "sTitle": "工号",
                "sDefaultContent": "",
                "sClass": "center"
            }, {
                "mDataProp": "",
                "sTitle": "用户状态",
                "sDefaultContent": "",
                "sClass": "center menuStatus"
            },{
                "mDataProp": "createTime",
                "sTitle": "创建时间",
                "sDefaultContent": "",
                "sClass": "center"
            }, {
                "mDataProp": "operate",
                "sTitle": "操作",
                "sDefaultContent": "",
                "sClass": "center handle-td"
            }
        ],
        "fnRowCallback": function(nRow, aData, iDisplayIndex) {
            var btnStr = "";
            btnStr += " <a class='operation-btn'>\
                                <img src='img/operation.png' width='20px' height='20px' />\
                                <div class='operation-none' >\
                                    <dl class='operation oper-triangle'>\
                                        <dd><a href='javascript:;' data-btn='btns.edit' ng-click='decorateModify(\"" + iDisplayIndex + "\",$event)'>编辑</a></dd>\
                                        <dd><a href='javascript:;' data-btn='btns.jurisdiction' ng-click='decorateModify2($event, \"" + iDisplayIndex + "\")'>分配权限</a></dd>\
                                        <dd><a href='javascript:;' data-btn='btns.resetPasswords' ng-click='resetPasswords(\"" + iDisplayIndex + "\",$event)'>重置密码</a></dd>\
                                        <span class='z'>▲</span><span class='y'>▲</span>\
                                    </dl>\
                                </div>\
                            </a>";

                $(nRow).find(".handle-td").append($compile(btnStr)($scope));
				
                /*$(nRow).find(".operation-btn").on('click', function() {
                	alert(1)
                    var sopt = $(this).parent().find(".operation-none");
                    if (sopt.css('display') == 'none') {
                        sopt.show();
                        $scope.isCoverBgShow = true;
                        $scope.$apply();
                    } else {
                        sopt.hide();
                        $scope.isCoverBgShow = false;
                        $scope.$apply();
                    }
                });*/
            // btnStr += "<a href='javascript:;' class='btn btn-yellow' style='margin-right:10px;' data-btn='btns.bj' ng-click='decorateModify(\"" + iDisplayIndex + "\",$event)'>编辑</a>"
            // +"<a href='javascript:;' class='btn btn-yellow' style='margin-right:10px;' data-btn='btns.gn' ng-click='decorateModify2($event, \"" + iDisplayIndex + "\")'>分配权限</a>"
            // 			+"<a href='javascript:;' class='btn btn-yellow' style='margin-right:10px;' data-btn='btns.bj' ng-click='resetPasswords(\"" + iDisplayIndex + "\",$event)'>重置密码</a>";
            // $(nRow).find(".handle-td").append($compile(btnStr)($scope));
            
            var checkStr = "";
            checkStr += '<input type="checkbox" data-index="'+iDisplayIndex+'" value="'+$scope.myDatas.result[iDisplayIndex].id+'" class="checkchild" />';
            $(nRow).find(".handle-ck").append($compile(checkStr)($scope));
            
            //用户状态
		    var menuStatus = "";
		    if(aData.status == "AVAILABLE"){
		    	menuStatus = "可用";
		    } else if(aData.status == "DELETE"){
		    	menuStatus = "删除";
		    } else if(aData.status == "FORBID"){
		    	menuStatus = "禁止";
		    }
		    $(nRow).find(".menuStatus").append(menuStatus);
        },
        "fnDrawCallback": function(oSettings) {
            
        },
        "fnServerParams": function(aoData) {
            
        },
        "fnServerData": function(sSource,aData,fnCallback,dataTableObject) {
           	var obj = dataTableObject.oAjaxData,_baseParams = {
	            // 'landlordId':user.get('landlordId'),
	            'page':obj.iDisplayStart / obj.iDisplayLength + 1,
	            'rows':obj.iDisplayLength,
	            'search':'false',
	            'nd': '1494221804416',
	            // 'rows': 50,
	            // 'page': 1,
	            'order': "asc",
	            "userName": $scope.userName,
	            "phone": $scope.phone,
	  			'status': $scope.itemStatus.status
           	};

            var __data = angular.extend({},_baseParams,obj.queryParams);
            rest.decoJava({
	           	type: 'post',
	            url: sSource,
	            data: __data,
	           	beforeSend: function(request){
					request.setRequestHeader("token", token); 
				},
	            success: function(data){
	               	$scope.myDatas = data;
	                var data1 = {
	                     'aaData': data.result,
	                     'sEcho': obj.sEcho,
	                     'iTotalDisplayRecords': data.pager.recordCount,
	                     'iTotalRecords': data.records,
	                };
	                fnCallback(data1);
	                //$(dataTableObject.nScrollBody).css('overflow', 'visible');
                    //$(dataTableObject.nScrollBody).css('margin-bottom', 60 + 'px');
                    $(".dataTables_scroll").css("overflow", "auto");
        			$(".dataTables_scrollBody").css("overflow", "visible");
	            }
            })
            //搜索 说明 只要是点击的搜索就让page为1 并且刷新datatables目的是回到第一页
		    //说明 自定义搜索只需在点击搜索的时候改变下datatables传过去的参数 然后$scope.dataTable.fnClearTable()即可
		    $scope.search = function(){
		    	__data.page = 1;
		    	$scope.dataTable.fnClearTable();
		    }
        }
    }
    $(document).on("click",".operation-btn",function(ev){
    	ev.stopPropagation();
    	$(".operation-none").hide();
    	var that = $(this).siblings(".operation-none");
    	if(that.css("display") == "none"){
    		that.show();
    	} else{
    		that.hide();
    	}
    })
    $(document).on("click",function(){
    	$(".operation-none").hide();
    })
	$scope.coverBgHide = function() {
        $('.operation-none').hide();
        $scope.isCoverBgShow = false;
        // $scope.$apply();
    }
	//不能删除
    $scope.initFinish = function(dataTable) {
         $scope.dataTable = dataTable;
    }
    
    //后台用户编辑弹窗
    $scope.decorateModify = function (iDisplayIndex,e) {
        
        //权限控制
    	var nowId = this.btns.edit;
    	if(accessStr.indexOf(nowId) == -1){
    		layer.msg("你没有该操作权限", {
	        	offset:'t',
	        	icon: 2
			});
			return false;
    	}
        
        ngDialog.openConfirm({
          template: 'js/module/decorate/userEdit.html',
          resolve: {
            load: function() {
                return $ocLazyLoad.load('angularFileUpload').then(
                    function(){
                        return uiLoad.load(['js/module/decorate/userEdit.js'])
                    });
            }
          },
          data:$scope.myDatas.result[iDisplayIndex],
          scope: $scope,
          width: 1200,
          // height: 700
        }).then(function(data) {
              $scope.dataTable.fnClearTable();
        }, function(reason) {
              $scope.dataTable.fnClearTable();
        });
    }
    
    //重置密码
    $scope.resetPasswords = function(iDisplayIndex){
    	//权限控制
    	var nowId = this.btns.resetPasswords;
    	if(accessStr.indexOf(nowId) == -1){
    		layer.msg("你没有该操作权限", {
	        	offset:'t',
	        	icon: 2
			});
			return false;
    	}
    	var _uid = $scope.myDatas.result[iDisplayIndex].id; //当前这条数据的用户id
    	rest.decoJava({
    		type: 'post',
            url: '/tenancy-sys/admin/user/reset/password',
            data: {userId: _uid},
           	beforeSend: function(request){
				request.setRequestHeader("token", token); 
			},
            success: function(data){
               	console.log(data);
                if(data.code == "0000"){
                	layer.msg(data.message, {
			        	offset:'t',
			        	icon: 1,
						btn: ['确定'],
						yes: function(index){
							layer.close(index);
					    }
					});
                }
            }
    	})
    }
    
    //用户权限
    $scope.decorateModify2 = function (e, iDisplayIndex) {
    	//权限控制
    	var nowId = this.btns.jurisdiction;
    	if(accessStr.indexOf(nowId) == -1){
    		layer.msg("你没有该操作权限", {
	        	offset:'t',
	        	icon: 2
			});
			return false;
    	}
        var btn = $(e.target);
        ngDialog.openConfirm({
          template: 'js/module/decorate/userPermission.html',
          resolve: {
            load: function() {
                return $ocLazyLoad.load('angularFileUpload').then(
                    function(){
                        return uiLoad.load(['js/module/decorate/userPermission.js'])
                    });
            }
          },
          data:$scope.myDatas.result[iDisplayIndex],
          scope: $scope,
          width: 1200,
          // height: 700
        }).then(function(data) {
              $scope.dataTable.fnClearTable();
        }, function(reason) {
              $scope.dataTable.fnClearTable();
        });

    }
    
    //全部选中和取消
    $scope.allMenu = function(e){
    	var This = angular.element(e.target);
    	if(This.is(":checked")){
    		angular.element(".checkchild").prop("checked",true);
    	} else{
    		angular.element(".checkchild").prop("checked",false);
    	}
    };
    
    
    //新建后台用户
    $scope.newUser = function(iDisplayIndex,e){
    	
    	//权限控制
    	var nowId = this.btns.add;
    	if(accessStr.indexOf(nowId) == -1){
    		layer.msg("你没有该操作权限", {
	        	offset:'t',
	        	icon: 2
			});
			return false;
    	}
    	
        ngDialog.openConfirm({
          template: 'js/module/decorate/newUser.html',
          resolve: {
            load: function() {
                return $ocLazyLoad.load('angularFileUpload').then(
                    function(){
                        return uiLoad.load(['js/module/decorate/newUser.js'])
                    });
            }
          },
          data:"",
          scope: $scope,
          width: 1200,
          // height: 700
        }).then(function(data) {
              $scope.dataTable.fnClearTable();
        }, function(reason) {
              $scope.dataTable.fnClearTable();
        });
    };
    
    //删除
    $scope.deleteMenu = function(e){
    	
    	//权限控制
    	var nowId = this.btns.delete;
    	if(accessStr.indexOf(nowId) == -1){
    		layer.msg("你没有该操作权限", {
	        	offset:'t',
	        	icon: 2
			});
			return false;
    	}
    	
    	if($(".checkchild:checked").length == 0){
    		layer.msg("没有选中项", {
	        	offset:'t',
	        	icon: 2,
				time: 2000
			});
    	} else{
    		layer.msg("确定删除吗？", {
	        	offset:'t',
	        	icon: 3,
				time: 0, //不自动关闭
				btn: ['确定','取消'],
				yes: function(index){
					layer.close(index);
					//执行删除
					
					//执行删除 数据格式要求 要将数组转换成字符串 并截除最后的逗号
					var idArr = [];
		    		$(".checkchild").each(function(){
			    		if($(this).is(":checked")){
			    			idArr.push($(this).val());
			    		}
			    	});
			    	var _idstring = "";
			    	angular.forEach(idArr,function(data){
			    		_idstring += data+',';
			    	})
			    	var _idstring = _idstring.substring(0,_idstring.length-1);
		    		rest.decoJava({
		    			type: 'post',
			            url: '/tenancy-sys/admin/user/batchDelete',
			            data: {"ids":_idstring},
			            beforeSend: function(request){
							request.setRequestHeader("token", token); 
						},
			            success: function (result) {
			            	if(result.code == "0000"){
				            	layer.msg(result.message, {
						        	offset:'t',
						        	icon: 1,
									time: 0, //不自动关闭
									btn: ['确定'],
									yes: function(index){
										layer.close(index);
										$scope.dataTable.fnClearTable();
								    }
								});
							} else{
								layer.msg(result.message, {
						        	offset:'t',
						        	icon: 5,
									time: 0, //不自动关闭
									btn: ['确定'],
									yes: function(index){
										layer.close(index);
								    }
								});
							}
			            }
			        });
			    }
			});
    	}
    };
    
    //顶部编辑
    $scope.menueditTop = function(){
    	
    	//权限控制
    	var nowId = this.btns.edit;
    	if(accessStr.indexOf(nowId) == -1){
    		layer.msg("你没有该操作权限", {
	        	offset:'t',
	        	icon: 2
			});
			return false;
    	}
    	
    	if($(".checkchild:checked").length == 0){
    		layer.msg("没有选中项", {
	        	offset:'t',
	        	icon: 2,
				time: 2000
			});
    	} else if($(".checkchild:checked").length >= 2){
    		layer.msg("一次只能编辑一项", {
	        	offset:'t',
	        	icon: 2,
				time: 2000
			});
    	} else{
    		var iDisplayIndex = parseInt($(".checkchild:checked").attr("data-index"));
    		$scope.decorateModify(iDisplayIndex)
    	}
    }

});
